package com.feature.shop.core.webmvc;

import org.apache.commons.lang3.StringUtils;
import org.springframework.web.method.HandlerMethod;
import org.springframework.web.servlet.AsyncHandlerInterceptor;

import com.feature.core.constant.SecurityConstants;
import com.feature.core.security.SecurityContextHolder;
import com.feature.core.util.JwtUtils;
import com.feature.core.util.WebUtil;
import com.feature.shop.auth.api.cache.AuthCache;
import com.feature.shop.auth.api.vo.LoginUserVo;

import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;

/**
 * 自定义请求头拦截器，将Header数据封装到线程变量中方便获取 注意：此拦截器会同时验证当前用户有效期自动刷新有效期
 */
public class LoginUserInterceptor implements AsyncHandlerInterceptor {
	@Override
	public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
		if (!(handler instanceof HandlerMethod)) {
			return true;
		}

		String token = WebUtil.getToken(request);
		if (StringUtils.isNotBlank(token)) {
			Integer usreId = JwtUtils.getValue(token, SecurityConstants.USER_ID_KEY);
			LoginUserVo vo = AuthCache.getLoginUserInfo(usreId);
			SecurityContextHolder.set(SecurityConstants.LOGIN_USER_KEY, vo);
		}
		return true;
	}

	@Override
	public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) throws Exception {
		SecurityContextHolder.remove();
	}
}
